package Monitoring;
import java.awt.AWTException;
import java.awt.Robot;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.JOptionPane;
public class StatusReader {

	private int logFileCount = -1;
	
	private File logFolder;
	private boolean programRunning = false;
	private Thread gameThread = null; 
	private Thread fileThread = null;
	private Object lock = new Object();
	private Settings settings;
	
	public StatusReader(Settings settings){
		logFolder =  new File(settings.getFileDirectory());
		if(logFolder.exists()){
			this.logFileCount = logFolder.list().length;
		}
		
		this.settings = settings;
	}
	
	public boolean startProgram(){
		if(logFileCount == -1){
			logFolder =  new File(settings.getFileDirectory());
			if(logFolder.exists()){
				this.logFileCount = logFolder.list().length;
			}else{
				JOptionPane.showMessageDialog ( 
						   null, "There was an error with your set log directory, please point it to the League Of Legends log directory" );
				return false;
			}
		}
		programRunning = true;
		startGameListening();
		System.out.println("Starting program");
		return true;
	}
	
	public void stopProgram(){
		programRunning = false;
	}
	
	private String getLatestLog(){
		File latestFile = null;
		long latestTime = -1;
		for(File file : logFolder.listFiles()){
			if(file.lastModified() > latestTime){
				latestTime = file.lastModified();
				latestFile = file;
			}
		}
		return latestFile.getPath();
	}
	
	//Starts looking for new files created which symbolize a game started
	private void startGameListening(){
		fileThread = new Thread(new fileCreationListener());
		fileThread.start();
		
	}
	
	//Starts reading a games files to see status in game
	private void startGameMonitoring(String filePath){

		gameThread= new Thread(new fileReadThread(filePath));
		gameThread.start();
		
	}
	
	private class fileCreationListener implements Runnable{
		
		public synchronized void run() {
			while(programRunning){
				if(newFileCreated() == false){
					delay(200);
					System.out.println("Waiting for game start");
				}else{
					startGameMonitoring(getLatestLog());
					synchronized (lock)
		            {
						gameThread = null;
		            }
				}
			}
		}
		
	}
	
	private class fileReadThread implements Runnable {

		String logFilePath;
		
		public fileReadThread(String logFilePath){
			this.logFilePath = logFilePath;
		}
		
	    public synchronized void run() {
    		Robot robot;
			try {
				robot = new Robot();
				
				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(logFilePath)));
					String line;
					while((line =reader.readLine()) == null || !line.contains("ALWAYS| Game exited") && programRunning){
						System.out.println(line);
						if(line == null){
							System.out.println("Waiting for log");
							
						} else if(line.contains("ALWAYS| PKT_StartGame")){
							System.out.println("Game started");
							robot.keyPress(settings.getIngameKey().getKeyCode());
							delay(200);
					        robot.keyRelease(settings.getIngameKey().getKeyCode());
						}else if(line.contains("ALWAYS| Sleeping")){
							System.out.println("Champion Loading");
							robot.keyPress(settings.getCharSelectionKey().getKeyCode());
							delay(200);
					        robot.keyRelease(settings.getCharSelectionKey().getKeyCode());
						
						}else{
							System.out.println("Sleeping");
						}
						delay(100);
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
		    	
				robot.keyPress(settings.getDefaultSceneKey().getKeyCode());
				delay(20);
		        robot.keyRelease(settings.getDefaultSceneKey().getKeyCode());
		    	System.out.println("Game ended");
			} catch (AWTException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			synchronized (lock)
            {
				 lock.notify();
            }
		   
	    }
	   
	    
	}
	
	private void delay(long time){
	    	try {
				Thread.sleep(time);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    }
	
	private boolean newFileCreated(){
		if(logFileCount < logFolder.listFiles().length ){
			logFileCount = logFolder.list().length;
			return true;
		}
		return false;
	}

}
